package cn.hsa.fqz.task.controller;

import cn.hsa.fqz.handler.base.BaseController;
import cn.hsa.fqz.task.entity.TTaskSqlExecute;
import cn.hsa.fqz.task.service.TTaskSqlExecuteService;
import cn.hsa.fqz.task.service.dto.LoginUserDTO;
import cn.hsa.fqz.task.service.dto.TTaskSqlExecuteDTO;
import cn.hsa.fqz.task.service.dto.TaskSqlExecuteConfigDTO;
import cn.hsa.hsaf.core.framework.context.HsafContextHolder;
import cn.hsa.hsaf.core.framework.util.CurrentUser;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * @author 刘隽
 * @version v1.0
 * @apiNote 功能描述:()
 * @date create in 2023/3/26 4:57
 */

@Slf4j
@Api(value = "任务脚本", tags = "任务脚本")
@RestController
@RequestMapping("/task")
public class TTaskSqlExecuteController extends BaseController {

    @Value("${zmjk.url.global}")
    private String globalUacmUrl;

    @Value("${zmjk.url.monitor}")
    private String monitorUrl;

    @Value("${zmjk.url.etl}")
    private String etlUrl;

    @Value("${zmjk.ck.host}")
    private String ckHost;

    @Value("${zmjk.ck.port}")
    private Integer ckPort;

    @Value("${zmjk.ck.passwd}")
    private String ckPasswd;

    @Autowired
    private TTaskSqlExecuteService tTaskSqlExecuteService;

    @ApiOperation(value = "新增脚本配置", notes = "新增脚本配置")
    @PostMapping("/add/taskSqlExcute")
    public WrapperResponse<Object> addTaskSqlExcute(@RequestBody TaskSqlExecuteConfigDTO dto){
        Integer result = tTaskSqlExecuteService.insertTaskSqlExecute(dto);
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "更新脚本配置", notes = "更新脚本配置")
    @PostMapping("/update/taskSqlExcute")
    public WrapperResponse<Object> updateTaskSqlExcute(@RequestBody TaskSqlExecuteConfigDTO dto){
        Integer result = tTaskSqlExecuteService.updateTaskSqlExecute(dto);
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "删除脚本配置", notes = "删除脚本配置")
    @GetMapping("/delete/taskSqlExcute")
    public WrapperResponse<Object> deleteTaskSqlExcute(@RequestParam("id") Integer id){
        Integer result = tTaskSqlExecuteService.deleteTaskSqlExecute(id);
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "禁用脚本配置", notes = "禁用脚本配置")
    @GetMapping("/disabled/taskSqlExcute")
    public WrapperResponse<Object> disableTaskSqlExcute(@RequestParam("id") Integer id,@RequestParam("status")Integer status){
        Integer result = tTaskSqlExecuteService.updateTaskSqlExecuteStatus(id,status);
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "获取执行脚本", notes = "获取执行脚本")
    @GetMapping("/getSqlExecuteByMenuId")
    public WrapperResponse<Object> getSqlExecuteByMenuId(
                                         @RequestParam("taskCode") String taskId) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUser = super.getLoginUser(currentUser);
        List<TTaskSqlExecute> list = tTaskSqlExecuteService.getMultiSQLByTaskId(loginUser,taskId);
        log.info("获取脚本信息: " + JSON.toJSONString(list));
        return WrapperResponse.success(list);
    }

    @ApiOperation(value = "获取线索主体执行脚本", notes = "获取线索主体执行脚本")
    @GetMapping("/getClueSqlExecuteByTaskCode")
    public WrapperResponse<Object> getClueSqlExecuteBytTaskId(
            @RequestParam("taskCode") String taskCode) {
        List<TTaskSqlExecute> list = tTaskSqlExecuteService.getClueSqlExecuteBytTaskId(taskCode);
        log.info("获取脚本信息: " + JSON.toJSONString(list));
        return WrapperResponse.success(list);
    }

    @ApiOperation(value = "执行任务SQL", notes = "执行任务SQL")
    @PostMapping("/execute/sql")
    public WrapperResponse<Object> executeSQL(@RequestBody TTaskSqlExecuteDTO execute) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUser = super.getLoginUser(currentUser);
        return tTaskSqlExecuteService.startTaskSqlExecute(loginUser,ckHost,ckPort,ckPasswd,execute.getExecute(),execute.getPage());
    }

    @ApiOperation(value = "导出任务线索详情", notes = "导出任务线索详情")
    @GetMapping("/export/clue")
    public void exportClue(@RequestParam("taskCode") String taskCode,HttpServletResponse response) {
        try {
            CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
            LoginUserDTO loginUser = super.getLoginUser(currentUser);
            String fileName =  "data-export-"+loginUser.getRegion()+"-"+DateFormatUtils.format(new Date(), "yyyy-MM-dd") + ".xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment; filename=data_export"+fileName);
            OutputStream os = null;
            os = response.getOutputStream();
            tTaskSqlExecuteService.exportClue(loginUser,ckHost, ckPort,ckPasswd,taskCode,os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "执行任务SQL", notes = "执行任务SQL")
    @PostMapping("/execute/sql/export")
    public void executeSQLAndExport(@RequestBody TTaskSqlExecuteDTO execute,HttpServletResponse response) {
        try {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUser = super.getLoginUser(currentUser);
        String fileName =  "data-export-"+loginUser.getRegion()+"-"+DateFormatUtils.format(new Date(), "yyyy-MM-dd") + ".xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment; filename=data_export"+fileName);
        OutputStream os = null;
        os = response.getOutputStream();
        tTaskSqlExecuteService.startTaskSqlExecuteAndExport(loginUser,ckHost,ckPort,ckPasswd,execute.getExecute(),os,execute.getExecute().getTabName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "执行demo-sql", notes = "执行demo-sql")
    @GetMapping("/demo/sql")
    public WrapperResponse<Object> executeCKDemo(@RequestParam("taskId") String taskId){
        return tTaskSqlExecuteService.executeCKDemo(ckHost,ckPort,ckPasswd,taskId);
    }

    @GetMapping("/redirect/monitor")
    public void redirectDatartDashboard(HttpServletResponse response){
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUser = super.getLoginUser(currentUser);
       String redrectUrl = tTaskSqlExecuteService.genMonitorUrl(loginUser,monitorUrl);
       log.info("跳转链接: " + redrectUrl);
        try {
            response.sendRedirect(redrectUrl);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    @GetMapping("/redirect/etl")
    public void redirectEtlDashboard(HttpServletResponse response){
        log.info("跳转链接: " + etlUrl);
        try {
            response.sendRedirect(etlUrl);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }
}
